using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Bludz
{
    class Model : Entity
    {
        Microsoft.Xna.Framework.Graphics.Model model;

        public Model() : base()
        {
            defaultVar<String>("model", "Models\\p1_wedge");
            defaultVar<Vector3>("rot", Vector3.Zero);
            defaultVar<Vector3>("pos", Vector3.Zero);
            defaultVar<Vector3>("scale", Vector3.One);

            EventServer.get().register("render", render);
        }

        public void render(String cmd, object[] args)
        {
            if (model == null)
                //model = ResourceManager<Microsoft.Xna.Framework.Graphics.Model>.get().getResource(getVar<string>("model"));
                model = GameServer.get().content.Load<Microsoft.Xna.Framework.Graphics.Model>(getVar<String>("model"));

            Vector3 pos = getVar<Vector3>("pos"),
                rot = getVar<Vector3>("rot"),
                scale = getVar<Vector3>("scale");
            Matrix[] transforms = new Matrix[model.Bones.Count];
            model.CopyAbsoluteBoneTransformsTo(transforms);
            Matrix view = Camera.get().getView();
            Matrix projection = Camera.get().getProjection();

            foreach (ModelMesh mesh in model.Meshes)
            {
                foreach (BasicEffect effect in mesh.Effects)
                {
                    effect.EnableDefaultLighting();
                    effect.World = transforms[mesh.ParentBone.Index] *
                        Matrix.CreateTranslation(pos) *
                        Matrix.CreateScale(scale) *
                        Matrix.CreateRotationX(rot.X) *
                        Matrix.CreateRotationY(rot.Y) *
                        Matrix.CreateRotationZ(rot.Z);
                    effect.View = view;
                    effect.Projection = projection;
                }
                mesh.Draw();
            }
        }
    }
}
